package com.example.dingdong.rest;

import java.io.File;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.example.dingdong.FilePath;
import com.example.dingdong.service.FileUploadAndDownloadService;
/**
 * 
 * @ClassName: FileUploadAndDownloadRest
 * @Description: 
 * @Author :chengwenixng
 * @DateTime 2022-03-25 13:01:16
 */
@RestController
@RequestMapping("/web/rest/FileUploadAndDownload")
public class FileUploadAndDownloadRest{ 
	//创建日志
	private static final Logger log = LoggerFactory.getLogger( FileUploadAndDownloadRest.class);
	
	@Autowired
	FileUploadAndDownloadService fileUploadAndDownloadService;

	/**
	 * 
	 * @Title: uploadFile
	 * @Description: 
	 * @Author coding
	 * @DateTime 2022-03-25 13:01:12
	 * @param file
	 * @return
	 */
	@RequestMapping("uploadFile")
	public JSONObject  uploadFile(@RequestParam("file") MultipartFile file){
		/**
		 * 预返回数据
		 */
		log.info("上传普通文件"+"fileName"+file.getOriginalFilename());
		JSONObject return_data = new JSONObject();
		JSONObject response = new JSONObject();
		return_data.put("cmd", "uploadFile");
		return_data.put("type", "response");
		return_data.put("response", response);
		try {
			String filePath =FilePath.CACHE_PATH+"/"+System.currentTimeMillis()+"_"
					+(int)((Math.random()*9+1)*100000)+"_"+file.getOriginalFilename();
			Boolean message=fileUploadAndDownloadService.uploadFile(file,filePath);
			if(message) {
				response.put("res", true);
				response.put("message", filePath);
			}else {
				response.put("res", false);
				response.put("exception", "上传失败！");
			}
		} catch (Exception e) {
			response.put("res", false);
			response.put("exception", e.getMessage());
		}
		System.out.println(response.toJSONString());
		return return_data;
	}
}
